package com.cib.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @描述:zset实现时间窗口限流
 * @Author: zhangh
 * @Time: 2021/8/16 14:37
 **/
@RestController
public class RedisController {
    @Value("#{${limit.lcount}}")
    private Integer lcount;
    @Value("#{${limit.ltime}}")
    private Integer ltime;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @GetMapping("zset")
    public String health(){

        boolean flag=isCurlimit("auth",ltime,lcount);
            if (flag){
                System.out.println("正常执行请求");
            }else{
                System.out.println("限流");
            }

        return "success";
    }

    private boolean isCurlimit(String auth, int ltime, int lcount) {
        long nowtimes = System.currentTimeMillis();
        //删除前60s的分数
         redisTemplate.opsForZSet().removeRangeByScore(auth, 0, nowtimes - ltime * 1000);
         //当前请求次数
        Long count = redisTemplate.opsForZSet().zCard(auth);
        System.out.println(count);
        if (count>=lcount){
            return false;
        }
        redisTemplate.opsForZSet().add(auth,nowtimes+"",nowtimes);
        return true;
    }
}
